
package com.mengmeizi.util;

import com.mengmeizi.R;
import com.mengmeizi.services.UpgradeService;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

public class Tools {
    /** 屏幕宽度 */
    private static int disWidth;

    /** 屏幕高度 */
    private static int disHeight;

    /** 屏幕密度 */
    private static float disDensity;

    private static int itemWidth, itemHeight;

    /** 判断内存卡状态 */
    public static boolean hasSDCard() {
        boolean result = false;
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            result = true;
        }
        return result;
    }

    /** 获取SDCard根路径 */
    public static String getSDCardPath() {
        File path = null;
        if (hasSDCard()) {
            // 获取根目录
            path = Environment.getExternalStorageDirectory();
            return path.toString();
        }
        return null;
    }

    /** 主动隐藏键盘 */
    public static void hideKeyboard(Activity owner) {
        try {
            InputMethodManager imm = (InputMethodManager) owner.getSystemService(Context.INPUT_METHOD_SERVICE);
            View view = owner.getCurrentFocus();
            if (view != null) {
                // imm.showSoftInput(view, 0); //显示软键盘
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);// 隐藏软键盘
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否有网络
     * 
     * @param context
     * @return
     */
    public static boolean hasNetwork(final Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    public static String sizeTransB(long size) {
        DecimalFormat df = new DecimalFormat("###.#");
        float f;
        if (size < 1024 * 1024) {
            f = ((float) size / 1024);
            return (df.format(new Float(f).doubleValue()) + "KB");
        } else {
            f = ((float) size / (float) (1024 * 1024));
            return (df.format(new Float(f).doubleValue()) + "MB");
        }
    }

    public static void showShortToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    public static void showLongToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }

    public static void switchActivity(Context context, Class<?> class1, Bundle bundle) {
        Intent intent = new Intent(context, class1);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        context.startActivity(intent);
    }

    /** 获取手机屏幕密度，并初始化各动态尺寸 */
    public static void setDensityValue(Activity owner) {
        DisplayMetrics metric = new DisplayMetrics();
        owner.getWindowManager().getDefaultDisplay().getMetrics(metric);
        disWidth = metric.widthPixels;
        disHeight = metric.heightPixels;
        disDensity = metric.density;
        itemWidth = (int) ((disWidth - 6 * disDensity - 4) / 3);
        // itemHeight = (int) (itemWidth / 0.75f);
    }

    /** 获得屏幕宽度 */
    public static int getDisplayWidth() {
        return disWidth;
    }

    /** 获得屏幕高度 */
    public static int getDisplayHeight() {
        return disHeight;
    }

    /** 获得屏幕密度 */
    public static float getDisplayDensity() {
        return disDensity;
    }

    /** 获得item的宽度（屏幕的三分之一） */
    public static int getItemWidth() {
        return itemWidth;
    }

    /** 获得item的高度（item的高度/0.75） */
    public static int getItemHeight() {
        return itemHeight;
    }

    /***
     * 测试用，模拟服务器数据
     * 
     * @return
     */
    public static String loadHttpData(Context context, String testFileName) {
        AssetManager am = null;
        ByteArrayOutputStream baos = null;
        String jsonData = null;
        InputStream is = null;
        try {
            am = context.getAssets();
            is = am.open(testFileName);
            baos = new ByteArrayOutputStream();
            int read = -1;
            while ((read = is.read()) != -1) {
                baos.write(read);
            }
            jsonData = new String(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException ie) {
                ie.printStackTrace();
            }
        }
        return jsonData;
    }

    public static void showNotification(Context context, String title, String message, String url) {
        Notification notification = new Notification(R.drawable.icon, title, System.currentTimeMillis());
        Intent intent = new Intent(context, UpgradeService.class);
        intent.putExtra("downUrl", url);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(context, title, message, pendingIntent);
        NotificationManager notifyManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notifyManager.notify(Const.NOTIFY_ID, notification);
    }

}
